﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _00365.Biz
{
    public class UserGroups
    {

        public static void Add(Data.UserGroup group)
        {
            DBInstance.Models.AddToUserGroups(group);
            DBInstance.Models.SaveChanges();
        }

        public static void Update(Data.UserGroup userGroup)
        {
            DBInstance.Models.SaveChanges();
        }

        public static List<Data.UserGroup> GetAll()
        {
            var items = from i in DBInstance.Models.UserGroups
                        orderby i.Name
                        select i;

            if (items != null)
                return items.ToList<Data.UserGroup>();

            return null;
        }

        public static void Remove(Guid Id)
        {
            Data.UserGroup group = (from i in DBInstance.Models.UserGroups
                                    where i.Id.Equals(Id)
                                    select i).FirstOrDefault();
            if (group != null)
            {
                DBInstance.Models.UserGroups.DeleteObject(group);
                DBInstance.Models.SaveChanges();
            }
        }

        public static Data.UserGroup Get(Guid Id)
        {
            Data.UserGroup group = (from i in DBInstance.Models.UserGroups
                                    where i.Id.Equals(Id)
                                    select i).FirstOrDefault();
            if (group != null) return group;
            return null;
        }

        public static bool AddUserToGroup(Data.UserGroup group, Data.Login user)
        {
            if (!group.Logins.Contains(user))
            {
                group.Logins.Add(user);
                DBInstance.Models.SaveChanges();
                return true;
            }
            return false;
        }

        public static bool RemoveUserFromGroup(Data.UserGroup group, Data.Login user)
        {
            if (group.Logins.Contains(user))
            {
                group.Logins.Remove(user);
                DBInstance.Models.SaveChanges();
                return true;
            }
            return false;
        }
    }
}